package docker

import (
	"context"
	"io"
	"time"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/api/types/strslice"
	"github.com/docker/docker/client"
)

var dockerCli *client.Client

// InitDockerClient 初始化 Docker 客户端（从环境变量或默认 socket）
func InitDockerClient() error {
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		return err
	}
	dockerCli = cli
	return nil
}

// ListAllContainers 列出所有容器（all==true 包含停止容器）
func ListAllContainers(ctx context.Context, all bool) ([]types.Container, error) {
	opts := types.ContainerListOptions{All: all}
	return dockerCli.ContainerList(ctx, opts)
}

// ListContainersByFilter 按 name 或 label 过滤容器
func ListContainersByFilter(ctx context.Context, all bool, name string) ([]types.Container, error) {
	args := filters.NewArgs()
	if name != "" {
		args.Add("name", name)
	}
	opts := types.ContainerListOptions{All: all, Filters: args}
	return dockerCli.ContainerList(ctx, opts)
}

// CreateNewContainer 创建容器，返回 containerID
func CreateNewContainer(ctx context.Context, image string, cmd []string, name string, env []string) (string, error) {
	cfg := &container.Config{
		Image: image,
		Cmd:   strslice.StrSlice(cmd),
		Env:   env,
		Tty:   false,
	}
	hostCfg := &container.HostConfig{
		AutoRemove: false,
	}

	resp, err := dockerCli.ContainerCreate(ctx, cfg, hostCfg, nil, nil, name)
	if err != nil {
		return "", err
	}
	return resp.ID, nil
}

// StartContainerByID 启动容器
func StartContainerByID(ctx context.Context, id string, timeoutSec int) error {
	ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSec)*time.Second)
	defer cancel()
	return dockerCli.ContainerStart(ctx, id, types.ContainerStartOptions{})
}

// StopContainerByID 停止容器
func StopContainerByID(ctx context.Context, id string, timeoutSec int) error {
	options := container.StopOptions{
		Timeout: &timeoutSec,
	}
	return dockerCli.ContainerStop(ctx, id, options)
}

// RemoveContainerByID 删除容器
func RemoveContainerByID(ctx context.Context, id string, force bool) error {
	opts := types.ContainerRemoveOptions{
		Force:         force,
		RemoveVolumes: false,
	}
	return dockerCli.ContainerRemove(ctx, id, opts)
}

// ContainerLogsReader 获取容器日志的 io.ReadCloser
func ContainerLogsReader(ctx context.Context, id string, follow bool, tail string) (io.ReadCloser, error) {
	opts := types.ContainerLogsOptions{
		ShowStdout: true,
		ShowStderr: true,
		Follow:     follow,
		Timestamps: false,
		Tail:       tail,
	}
	return dockerCli.ContainerLogs(ctx, id, opts)
}

// ListImages 列出镜像
func ListImages(ctx context.Context) ([]types.ImageSummary, error) {
	return dockerCli.ImageList(ctx, types.ImageListOptions{})
}

// PullImage 拉取镜像
func PullImage(ctx context.Context, image string) (io.ReadCloser, error) {
	opts := types.ImagePullOptions{}
	rc, err := dockerCli.ImagePull(ctx, image, opts)
	if err != nil {
		return nil, err
	}
	return rc, nil
}
